package com.example.securitydemo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;

public class DemoAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        DemoResult demoResult = new DemoResult();
        demoResult.setCode(-1);
        demoResult.setMessage("无权限");
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(demoResult);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(json);
    }
}
